package cn.ch.train.generator.util;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

public class FreemarkerUtil {

    /**
     * FTL（FreeMarker Template Language）
     * 约定：所有的模板文件都放在这个路径下
     */
    static String ftlPath = "generator/src/main/java/cn/ch/train/generator/ftl/";
    static Template template;
    public static void initConfig(String ftlName) throws IOException {
        Configuration config = new Configuration(Configuration.VERSION_2_3_31);
        // 约定好ftl的路径
        config.setDirectoryForTemplateLoading(new File(ftlPath));
        config.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_31));
        template = config.getTemplate(ftlName);
    }

    public static void generator(String fileName, Map<String, Object> map) throws IOException, TemplateException {
        FileWriter fileWriter = new FileWriter(fileName);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        // 开始处理，map中是放的变量替换，比如param.put("domain", "Test");就是将模板文件中的domain替换为Test
        template.process(map, bufferedWriter);
        bufferedWriter.flush();
        fileWriter.close();
    }
}
